//
//  TempLovExtesion.swift
//  ANOA
//
//  Created by 邱仙凯 on 2023/7/12.
//  Copyright © 2023 zwb. All rights reserved.
//  lov   下拉选    跟随接口

import UIKit

extension ConfigMenuForm  {
    // onexx 模板   indexPath  细表的索引
    func showLov(onexx:TemplateModel,indexPath:IndexPath?) {
        
        var detDic:[String:Any]?
        if indexPath.isSome {
            detDic = self.detHandler[self.cDIndex][indexPath!.section].dic
        }
        
        
        if onexx.is_multichoice == "1" {
            // 多选不能分页，所以把所有参数都装了，包括 page  size都当固定的装了
            let pathDic = url2PathDic(mainDic: self.main,currDetaiDic: detDic,arr: onexx.pathHandler.comPa + onexx.pathHandler.spePa)

            // 多选
            KSNetwork.shared.doRequest(API.temp(.path(path: onexx.pathHandler.path, paramDic: pathDic))) { (data:BaseResult<OperateResult>) in
                if data.flag == TRUE {
                    
                    var allArr = [([String:Any],Bool)]()
                    for i in 0..<data.infoDicArr.count {
                        allArr.append((data.infoDicArr[i],false))
                    }
                    
                    let cle:([Any])->() = { arr in
                        
                        let infosx = arr.compactMap{ $0 as? [String:Any] }
                        self.dealFill(backFillArr: onexx.lovBackFillArr, infos: infosx, infoDic: nil)
                        

                        
                    }
                    let showC:((GlobalTableViewCell, Any) -> ()) = { cell, model in
                        
                        var contArr = [(String,String?)]()
                        
                        for item in onexx.lovShowArr {
                            let pre = item.preChar(char: ":").unwrap
                            let suf = item.sufChar(char: ":").unwrap
                            contArr.append((suf,any2Str((model as! [String:Any])[pre])))
                        }
                        
                        cell.setDataSource(contentArr: contArr)
                        
                    }
                    let filterC:((Any, String) -> (Bool)) = { model, keyword -> Bool in
                        var vvA = [String]()
                        for item in onexx.lovShowArr {
                            let pre = item.preChar(char: ":").unwrap
                            //                                        let suf = item.sufChar(char: ":").unwrap
                            vvA.append(any2Str((model as! [String:Any])[pre]))
                        }
                        let vvS = vvA.joined(separator: ",")
                        return vvS.contains(keyword)
                    }
                    let vc = KSMultiSelectUtil.initWithNav(title: "选择", allArr: allArr ,backClosure: cle,kSShowCell: showC , filterClosure: filterC)
                    self.present_FullScreen(to: vc)
                } else {
                    KSToast(data.errorCombine.unwrap)
                }
            }
            
            
            
        } else {
            var pathDic = url2PathDic(mainDic: self.main,currDetaiDic: detDic,arr: onexx.pathHandler.comPa)

            
            
            
            // 单选
            let keyPa = onexx.pathHandler.spePa.filter{ $0.contains("keyword") }
            let showSearch:Bool = (keyPa.count > 0)
            let sizePa = onexx.pathHandler.spePa.filter{ $0.contains("size") }
            let vc = KSSingleSelectNetUtil(searchType:showSearch ? .barAndScan : .none)
            vc.title = "选择"
            
            if sizePa.count > 0,intTran(sizePa.first!.sufChar(char: "=")) > 0 {
                vc.size = intTran(sizePa.first!.sufChar(char: "="))
            } else {
                vc.size = 0 // 0为不分页
            }
            vc.kSSingleSelectNetNetwork = { page,size,keyword in
                if showSearch {
                    for ii in 0..<keyPa.count {
                        pathDic.updateValue(keyword, forKey: keyPa[ii].preChar(char: "=").unwrap)
                    }
                }
                if size != 0 {
                    pathDic.updateValue("\(page)", forKey: "page")
                    pathDic.updateValue("\(size)", forKey: "size")
                }
                KSNetwork.shared.doRequest(API.temp(.path(path: onexx.pathHandler.path, paramDic: pathDic))) { (data:BaseResult<OperateResult>) in
                    if data.flag == TRUE {
                        if page == 1 {
                            vc.allArr.removeAll()
                        }
                        vc.showData(arr:data.infoDicArr)
                        
                    } else {
                        
                        alertUtil(title: data.errorCombine.unwrap, withCancel: false,operateS: [nameAction(name: "确认", action: { _ in
                            self.navigationController?.popViewController(animated: true)
                        })])
                        
                    }
                }
            }
            vc.kSSingleSelectNetShowCell = { cell,model in
                
                var contArr = [(String,String?)]()
            
                
                for item in onexx.lovShowArr {
                    let pre = item.preChar(char: ":").unwrap
                    let suf = item.sufChar(char: ":").unwrap
                    contArr.append((suf,any2Str((model as! [String:Any])[pre])))
                }
                
                cell.setDataSource(contentArr: contArr)
                
                
            }
            vc.backClosure = { [indexPath] model in
             
                self.commonSingleSelectBackFill(onexx: onexx,indexPath: indexPath,dicc:(model as! [String:Any]))
            }
            
            self.navigationController?.pushViewController(vc,animated:true)
            
        }
        
        
    }
   
    // 通用的lov回填，
    func commonSingleSelectBackFill(onexx:TemplateModel,indexPath:IndexPath?,dicc:[String:Any]) {
      
        TempLog("\n\n\n【lov单选回填】")
       var mainEffected = false
        var detEffected = false
        for item in onexx.lovBackFillArr {
            let pre = item.preChar(char: ":").unwrap
            var suf = item.sufChar(char: ":").unwrap
            
            if suf.contains("b.") {
                suf = suf.replacingOccurrences(of: "b.", with: "")
                 TempLog("\(pre)-->(b.)\(suf) 值:\(dicc[pre].unwrap)")

                if indexPath.isSome {
                    self.detHandler[self.cDIndex][indexPath!.section].dic[suf] = dicc[pre]
                } else {
                    for i in 0..<self.detHandler[self.cDIndex].count {
                        self.detHandler[self.cDIndex][i].dic[suf] = dicc[pre]
                     }
                 }
                detEffected = true
            } else if suf.contains("a.")  {
                suf = suf.replacingOccurrences(of: "a.", with: "")
                 TempLog("\(pre)-->(a.)\(suf) 值:\(dicc[pre].unwrap)")
               self.main[suf] = dicc[pre]
                mainEffected = true
            } else if suf.contains(".") {
                //定义的细表回填
                let dPaNm = suf.preChar(char: ".").unwrap
               let realP = suf.sufChar(char: ".").unwrap

                TempLog("\(pre)-->(\(dPaNm).)\(realP) 值:\(dicc[pre].unwrap)")
                
                if let dIndex = self.rootTemp.multiDetailsParams.getIndexFor({ one in
                    one == dPaNm
                }) {
                   self.detHandler[dIndex][indexPath!.section].dic[realP] = dicc[pre]
                   detEffected = true
               } else {
                   TempLog("找不到，排查回填细表参数")

               }
                
                
            } else {
                 // 没配位置 则根据发起位置回填
                if indexPath.isSome {
                    TempLog("\(pre)-->(默认b.)\(suf) 值:\(dicc[pre].unwrap)")
                    self.detHandler[self.cDIndex][indexPath!.section].dic[suf] = dicc[pre]
                    detEffected = true
                } else {
                    TempLog("\(pre)-->(默认a.)\(suf) 值:\(dicc[pre].unwrap)")
                   self.main[suf] = dicc[pre]
                    mainEffected = true
                }
                
                
            }
     
        }
        
         if mainEffected {
            self.configTempDataSource()
         } else {
             if detEffected {
                 self.reloadDetData()
             }
         }
        self.continueUrl(onexx: onexx,indexPath: indexPath)
       
    }

 
    func showAreaLov(onexx: TemplateModel, indexPath: IndexPath?) {
        let vc = ProCityUtil(selectType: .proCityDict)
        let nav = BaseNavigationController(rootViewController: vc)
        vc.tripleSelectClosure = { pro, city, dist in
            let value = "\(pro)-\(city)-\(dist)"
            
            var dict = [String: String]()
            onexx.lovLDShowArr.forEach { key in
                dict[key] = value
            }
            self.commonSingleSelectBackFill(onexx: onexx, indexPath: indexPath, dicc: dict)
        }
        self.present_FullScreen(to: nav)
    }
}
